import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { message } from 'antd';

import {
  queryPartitionList,
  queryStatusList,
  queryOrderList,
} from './service';
import { fetchValidation } from '@/utils';

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: {};
  effects: {
    fetch: Effect;
    fetchStatus: Effect;
  };
  reducers: {
    save: Reducer;
    saveStatus: Reducer;
    clear: Reducer;
  };
}

const stateInfo = {
  dataInfo: {
    list: [],
    count: 0,
  },
  statusList: [],
};

const Model: ModelType = {
  namespace: 'partitionOrder',

  state: stateInfo,

  effects: {
    * fetch({ payload }, { call, put }) {
      const response = yield call(queryOrderList, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'save',
        payload: response.body,
      });
    },

    * fetchStatus({ payload }, { call, put }) {
      const response = yield call(queryStatusList, payload);
      const data = fetchValidation(response);
      const { body }: any = data;
      const list = Object.entries(body).map((item: any) => ({
        value: Number(item[0]),
        label: item[1],
      }));
      yield data && put({
        type: 'saveStatus',
        payload: list,
      });
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        dataInfo: action.payload,
      };
    },

    saveStatus(state, { payload }) {
      return {
        ...state,
        statusList: payload,
      };
    },

    clear() {
      return stateInfo;
    },
  },
};

export default Model;
